﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmoLiteApi.Sql;
using System.Data.SqlClient;
using SmoLiteApi.Helper;

namespace SmoLiteApi
{
    /// <summary/>
    public class User
    {
        private Database _database;
        private string _name;
        private string _logon;

        /// <summary/>
        public User(
            Database database,
            string name)
        {
            this._database = database;
            this._name = name;
        }

        /// <summary/>
        public string Name
        {
            get { return this._name; }
            set { this._name = value; }
        }

        /// <summary/>
        public string Logon
        {
            get { return this._logon; }
            set { this._logon = value; }
        }

        /// <summary/>
        public void Create()
        {
            UserCreateSql userCreateSql = new UserCreateSql();

            // set attributes
            userCreateSql.AddObject(new { Name = this._name });

            // was it set
            if (!string.IsNullOrWhiteSpace(this._logon))
            {
                userCreateSql.AddObject(new { Logon = this._logon });
            }

            using (SqlCommandHelper sqlCommandHelper = SqlCommandHelper.FetchSqlCommand(this._database.SqlConnection, userCreateSql.Render()))
            {
                // run the command
                sqlCommandHelper.ExecuteNonQuery();
            }
        }

        /// <summary/>
        public void AddToRole(string role)
        {
            using (SqlCommandHelper sqlCommandHelper = SqlCommandHelper.FetchProcedureCommand(this._database.SqlConnection, Constant.PROCEDURE_USER_ROLE_TO_MEMBER))
            {
                // set inputs
                sqlCommandHelper.Parameters.Add(new SqlParameter(Constant.PARAMETER_MEMBER_NAME, this._name));
                sqlCommandHelper.Parameters.Add(new SqlParameter(Constant.PARAMETER_ROLE_NAME, role));

                // run the command
                sqlCommandHelper.ExecuteNonQuery();
            }
        }

        /// <summary/>
        public void Drop()
        {
            UserDropSql userDropSql = new UserDropSql();

            // set attributes
            userDropSql.AddObject(new { Name = this._name });

            using (SqlCommandHelper sqlCommandHelper = SqlCommandHelper.FetchSqlCommand(this._database.SqlConnection, userDropSql.Render()))
            {
                // run the command
                sqlCommandHelper.ExecuteNonQuery();
            }
        }
    }
}
